import { DataString } from "../data.mts";

const query = async () => {
  let result = 0,
    count = 0;
  const data: Record<string, Record<string, Blob>> = {};
  const workers = await navigator.serviceWorker.getRegistrations();
  const keys = await caches.keys();
  for (const key of keys) {
    const respBlob: Record<string, Blob> = {};
    const opened = await caches.open(key);
    const resps = await opened.matchAll();
    result += key.length;
    for (const resp of resps) {
      const blob = await resp.blob();
      result += blob.size;
      respBlob[resp.url] = blob;
      count++;
    }
    data[key] = respBlob;
  }
  return { count, result, data, workers: workers.length };
};

const clear = async (type: 1 | 2 | 3) => {
  if ((type & 2) === 2) {
    const workers = await navigator.serviceWorker.getRegistrations();
    for (const worker of workers) {
      await worker.unregister();
    }
  }

  if ((type & 1) === 1) {
    const keys = await caches.keys();
    for (const key of keys) {
      await caches.delete(key);
    }
  }
};

const summary = (
  data: Awaited<ReturnType<typeof query>>,
) => `${DataString.Cache}：
服务数量 ${String(data.workers)}
离线缓存数量 ${String(data.count)}
离线缓存大小 ${String(data.result)}`;

const stringify = (data: Awaited<ReturnType<typeof query>>) => {
  let prompts = "";
  const sks = Object.keys(data.data);
  for (const [index, skey] of sks.entries()) {
    const cache = data.data[skey] ?? {};
    prompts += `------
存储 ${[index + 1, sks.length].join("/")} ：${skey}
数量：${String(Object.keys(cache).length)}
`;
    for (const key of Object.keys(cache)) {
      prompts += `------
地址：${key}
大小：${String(cache[key].size)}
`;
    }
  }
  return prompts;
};

export default { query, clear, summary, stringify };
